<?php
/**
 * Created by PhpStorm.
 * User: qufan
 * Date: 2016/12/6 0006
 * Time: 23:56
 */

/**
 * 判断是否登录
 * @return int
 */
function is_login(){
    $user = session('user_auth');
    if (empty($user)) {
        return 0;
    } else {
        return session('user_auth_sign') == data_auth_sign($user) ? $user['uid'] : 0;
    }
}

function logOperation($func, $desc){
    $model = D('OperationLog');
    $model->addLog($func, $desc);
}

function renameFile($is_icon, $filename, &$to){
//    $base_path = '';
    if($is_icon){
        $base_path = C('USER_ICON_PATH');
    }else{
        $base_path = C('MAILLIST_ICON_PATH');
    }
    if(file_exists($base_path . $filename)){
        $ext = pathinfo($base_path . $filename,PATHINFO_EXTENSION);
        $to = $to.'.'.$ext;
    }
    if ($filename == $to){
        return false;
    }
    if(rename($base_path . $filename, $base_path . $to)){
        return true;
    }else{
        return false;
    }

}

/**
 * 获得当前登录用户的角色id
 * @return int
 */
function get_role_id(){
    $user = session('user_auth');
    if (empty($user)){
        return 0;
    }else{
        return $user['role_id'];
    }
}

/**
 * 数据签名认证
 * @param $data
 * @return string
 */
function data_auth_sign($data){
    //数据类型检测
    if(!is_array($data)){
        $data = (array)$data;
    }
    ksort($data); //排序
    $code = http_build_query($data); //url编码并生成query字符串
    $sign = sha1($code); //生成签名
    return $sign;
}

/**
 * 时间戳格式化
 * @param int $time
 * @return string 完整的时间显示
 * @author huajie <banhuajie@163.com>
 */
function time_format($time = NULL,$format='Y-m-d H:i:s'){
    $time = $time === NULL ? NOW_TIME : intval($time);
    return date($format, $time);
}

function getFieldsDescr($fields){
    $result = array();
    $fieldToTitle = C('FIELD_TO_TITLE');
    foreach ($fields as $field){
        if(isset($fieldToTitle[$field])){
            if ($field == 'administrative_division_code'){
                $result[] = array('field' => 'administrative_division_name', 'title'=>'行政区划');
            }else{
                $result[] = array('field' => $field, 'title'=>$fieldToTitle[$field]);
            }

        }
    }
    return $result;
}

/**
 * 把返回的数据集转换成Tree
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @return array
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0, $text = 'text') {
    // 创建Tree
    $tree = array();
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $list[$key]['text'] = $list[$key][$text];
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId =  $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

//function http_json($url, $params = array(), $headers = array(), $method = 'get'){
//    $ch = curl_init();
//    curl_setopt($ch, CURLOPT_URL, $url);
//    curl_setopt($ch)
//}

//参数1：访问的URL，参数2：post数据(不填则为GET)，参数3：提交的$cookies,参数4：是否返回$cookies
function curl_request($url, $post='', $header = '',$cookie='', $returnCookie=0){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
//    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
//    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
//    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
//    curl_setopt($curl, CURLOPT_REFERER, "http://XXX");
    if($post) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
    }
    if($header){
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    }
    if($cookie) {
        curl_setopt($curl, CURLOPT_COOKIE, $cookie);
    }
//    curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
    curl_setopt($curl, CURLOPT_TIMEOUT, 10);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
    if (curl_errno($curl)) {
        return curl_error($curl);
    }
    curl_close($curl);
    if($returnCookie){
        list($header, $body) = explode("\r\n\r\n", $data, 2);
        preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
        $info['cookie']  = substr($matches[1][0], 1);
        $info['content'] = $body;
        return $info;
    }else{
        return $data;
    }
}

/**
 * 去掉url中的参数
 * @param $url
 */
function clear_url_param($url){
    $tmp=parse_url($url);
    $rs =empty($tmp['scheme'])?'http://':$tmp['scheme'].'://';
    $rs.=$tmp['host'].$tmp['path'];
    return $rs;
}


/**
 * 用于生成chat_id
 * @return string
 */
function generate_duty_id(){
    list($usec, $sec) = explode(" ", microtime());
    $usec = intval($usec * 1000);
    return 'dr'. date('YmdHis', $sec) . $usec;
}

function get_week($date){
    //强制转换日期格式
    $date_str=date('Y-m-d',strtotime($date));
    //封装成数组
    $arr=explode("-", $date_str);
    //参数赋值
    //年
    $year=$arr[0];
    //月，输出2位整型，不够2位右对齐
    $month=sprintf('%02d',$arr[1]);
    //日，输出2位整型，不够2位右对齐
    $day=sprintf('%02d',$arr[2]);
    //时分秒默认赋值为0；
    $hour = $minute = $second = 0;
    //转换成时间戳
    $strap = mktime($hour,$minute,$second,$month,$day,$year);
    //获取数字型星期几
    $number_wk=date("w",$strap);
    //自定义星期数组
    $weekArr=array("星期日","星期一","星期二","星期三","星期四","星期五","星期六");
    //获取数字对应的星期
    return $weekArr[$number_wk];
}
